<template>
  <div class="invoices">
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="发票号码">
          <el-input v-model="searchForm.invoiceNo" placeholder="请输入发票号码" clearable />
        </el-form-item>
        <el-form-item label="发票类型">
          <el-select v-model="searchForm.type" placeholder="请选择发票类型" clearable>
            <el-option label="增值税专用发票" value="special" />
            <el-option label="增值税普通发票" value="normal" />
            <el-option label="其他发票" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待开具" value="pending" />
            <el-option label="已开具" value="issued" />
            <el-option label="已作废" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="button-group">
      <el-button type="primary" @click="handleAdd" v-if="hasPermission('finance:invoice:add')">
        <el-icon><Plus /></el-icon>新增发票
      </el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
    </div>

    <div class="card">
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column prop="invoiceNo" label="发票号码" width="150" />
        <el-table-column prop="type" label="发票类型" width="150">
          <template #default="{ row }">
            <el-tag :type="getInvoiceTypeType(row.type)">
              {{ getInvoiceTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="200" />
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="taxRate" label="税率" width="100">
          <template #default="{ row }">
            {{ row.taxRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="taxAmount" label="税额" width="120">
          <template #default="{ row }">
            ¥{{ row.taxAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="价税合计" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="issueDate" label="开具日期" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)" v-if="hasPermission('finance:invoice:edit') && row.status === 'pending'">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)" v-if="hasPermission('finance:invoice:delete') && row.status === 'pending'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" @close="handleDialogClose">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发票类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择发票类型" style="width: 100%">
                <el-option label="增值税专用发票" value="special" />
                <el-option label="增值税普通发票" value="normal" />
                <el-option label="其他发票" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户" prop="customerId">
              <el-select v-model="form.customerId" placeholder="请选择客户" style="width: 100%">
                <el-option
                  v-for="customer in customers"
                  :key="customer.id"
                  :label="customer.name"
                  :value="customer.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="税率" prop="taxRate">
              <el-input-number v-model="form.taxRate" :min="0" :max="100" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开具日期" prop="issueDate">
              <el-date-picker
                v-model="form.issueDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>

        <el-form-item label="发票明细">
          <div class="invoice-items">
            <div
              v-for="(item, index) in form.items"
              :key="index"
              class="invoice-item"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item :label="'商品' + (index + 1)" :prop="`items.${index}.productName`">
                    <el-input v-model="item.productName" placeholder="商品名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="数量" :prop="`items.${index}.quantity`">
                    <el-input-number v-model="item.quantity" :min="1" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="单价" :prop="`items.${index}.price`">
                    <el-input-number v-model="item.price" :min="0" :precision="2" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-button type="danger" @click="removeItem(index)" :disabled="form.items.length === 1">
                    删除
                  </el-button>
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" @click="addItem">添加商品</el-button>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

const hasPermission = (permission) => {
  return userStore.hasPermission(permission)
}

const searchForm = reactive({
  invoiceNo: '',
  type: '',
  status: ''
})

const tableData = ref([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const customers = ref([
  { id: 1, name: '客户A' },
  { id: 2, name: '客户B' },
  { id: 3, name: '客户C' }
])

const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref()

const form = reactive({
  id: null,
  type: '',
  customerId: '',
  taxRate: 13,
  issueDate: '',
  remark: '',
  items: [{ productName: '', quantity: 1, price: 0 }]
})

const formRules = {
  type: [{ required: true, message: '请选择发票类型', trigger: 'change' }],
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  taxRate: [{ required: true, message: '请输入税率', trigger: 'blur' }],
  issueDate: [{ required: true, message: '请选择开具日期', trigger: 'change' }],
  'items.0.productName': [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  'items.0.quantity': [{ required: true, message: '请输入数量', trigger: 'blur' }],
  'items.0.price': [{ required: true, message: '请输入单价', trigger: 'blur' }]
}

const mockData = [
  {
    id: 1,
    invoiceNo: 'INV-2024-001',
    type: 'special',
    customerName: '客户A',
    amount: 10000.00,
    taxRate: 13,
    taxAmount: 1300.00,
    totalAmount: 11300.00,
    status: 'issued',
    issueDate: '2024-01-15',
    remark: '销售发票'
  },
  {
    id: 2,
    invoiceNo: 'INV-2024-002',
    type: 'normal',
    customerName: '客户B',
    amount: 5000.00,
    taxRate: 13,
    taxAmount: 650.00,
    totalAmount: 5650.00,
    status: 'pending',
    issueDate: '',
    remark: ''
  }
]

const getInvoiceTypeType = (type) => {
  const typeMap = {
    special: 'primary',
    normal: 'success',
    other: 'info'
  }
  return typeMap[type] || 'info'
}

const getInvoiceTypeText = (type) => {
  const textMap = {
    special: '增值税专用发票',
    normal: '增值税普通发票',
    other: '其他发票'
  }
  return textMap[type] || '未知'
}

const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    issued: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待开具',
    issued: '已开具',
    cancelled: '已作废'
  }
  return statusMap[status] || '未知'
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, { invoiceNo: '', type: '', status: '' })
  handleSearch()
}

const loadData = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

const handleAdd = () => {
  dialogTitle.value = '新增发票'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑发票'
  Object.assign(form, {
    id: row.id,
    type: row.type,
    customerId: 1,
    taxRate: row.taxRate,
    issueDate: row.issueDate,
    remark: row.remark,
    items: [{ productName: '商品A', quantity: 1, price: 100 }]
  })
  dialogVisible.value = true
}

const handleView = (row) => {
  ElMessage.info('查看功能开发中...')
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个发票吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    ElMessage.success('删除成功')
    loadData()
  } catch {}
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

const addItem = () => {
  form.items.push({ productName: '', quantity: 1, price: 0 })
}

const removeItem = (index) => {
  form.items.splice(index, 1)
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    setTimeout(() => {
      ElMessage.success(form.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadData()
      submitLoading.value = false
    }, 1000)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const resetForm = () => {
  Object.assign(form, {
    id: null,
    type: '',
    customerId: '',
    taxRate: 13,
    issueDate: '',
    remark: '',
    items: [{ productName: '', quantity: 1, price: 0 }]
  })
}

const handleDialogClose = () => {
  resetForm()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.invoices {
  .invoice-items {
    .invoice-item {
      border: 1px solid $border-color-light;
      border-radius: 4px;
      padding: 15px;
      margin-bottom: 15px;
    }
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 